const todo = {
  namespaced: true,
  state: {
    // 待办任务列表
    todoList: [],
    // 未读数量
    unreadCount: 0,
    // 是否正在加载
    loading: false
  },
  
  mutations: {
    // 设置待办列表
    SET_TODO_LIST(state, list) {
      state.todoList = list
      state.unreadCount = list.filter(item => !item.isRead).length
    },
    
    // 添加待办任务
    ADD_TODO(state, todo) {
      state.todoList.unshift(todo)
      if (!todo.isRead) {
        state.unreadCount++
      }
    },
    
    // 标记为已读
    MARK_AS_READ(state, id) {
      const todo = state.todoList.find(item => item.id === id)
      if (todo && !todo.isRead) {
        todo.isRead = true
        state.unreadCount--
      }
    },
    
    // 批量标记为已读
    BATCH_MARK_AS_READ(state, ids) {
      ids.forEach(id => {
        const todo = state.todoList.find(item => item.id === id)
        if (todo && !todo.isRead) {
          todo.isRead = true
          state.unreadCount--
        }
      })
    },
    
    // 全部标记为已读
    MARK_ALL_AS_READ(state) {
      state.todoList.forEach(todo => {
        todo.isRead = true
      })
      state.unreadCount = 0
    },
    
    // 删除待办任务
    REMOVE_TODO(state, id) {
      const index = state.todoList.findIndex(item => item.id === id)
      if (index > -1) {
        const todo = state.todoList[index]
        if (!todo.isRead) {
          state.unreadCount--
        }
        state.todoList.splice(index, 1)
      }
    },
    
    // 批量删除
    BATCH_REMOVE_TODO(state, ids) {
      ids.forEach(id => {
        const index = state.todoList.findIndex(item => item.id === id)
        if (index > -1) {
          const todo = state.todoList[index]
          if (!todo.isRead) {
            state.unreadCount--
          }
          state.todoList.splice(index, 1)
        }
      })
    },
    
    // 设置加载状态
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    
    // 清空待办列表
    CLEAR_TODO_LIST(state) {
      state.todoList = []
      state.unreadCount = 0
    }
  },
  
  actions: {
    // 获取待办列表
    async fetchTodoList({ commit }, params = {}) {
      commit('SET_LOADING', true)
      try {
        const { getWarningList } = await import('@/api/assessAlert')
        // 默认只查询未读数据
        const queryParams = {
          isRead: 0, // 只查询未读
          ...params
        }
        const response = await getWarningList(queryParams)
        
        // 转换数据格式以匹配组件期望的结构
        let todoList = []
        if (response.code === 200) {
          const rawData = response.data || response.rows || []
          todoList = rawData.map(item => ({
            id: item.id,
            alertTitle: item.title,
            alertContent: item.description,
            alertType: item.type || 'SCORE_WARNING', // 默认类型
            isRead: item.isRead || false,
            createTime: item.createTime || new Date().toISOString(),
            problemUserName: item.userName,
            problemUserId: item.userId,
            userId: item.userId
          }))
        }
        
        commit('SET_TODO_LIST', todoList)
        return response
      } catch (error) {
        console.error('获取待办列表失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 添加待办任务
    addTodo({ commit, state }, todo) {
      // 检查是否已存在相同ID的任务，避免重复添加
      const existingTodo = state.todoList.find(item => item.id === todo.id)
      if (existingTodo) {
        return
      }
      
      commit('ADD_TODO', {
        ...todo,
        id: todo.id || Date.now() + Math.random(),
        isRead: false,
        createTime: todo.createTime || new Date().toISOString()
      })
    },
    
    // 标记为已读
    async markAsRead({ commit }, id) {
      try {
        const { markAsRead } = await import('@/api/assessAlert')
        await markAsRead(id)
        commit('MARK_AS_READ', id)
      } catch (error) {
        console.error('标记已读失败:', error)
        throw error
      }
    },
    
    // 批量标记为已读
    async batchMarkAsRead({ commit }, ids) {
      try {
        const { batchMarkAsRead } = await import('@/api/assessAlert')
        await batchMarkAsRead(ids)
        commit('BATCH_MARK_AS_READ', ids)
      } catch (error) {
        console.error('批量标记已读失败:', error)
        throw error
      }
    },
    
    // 全部标记为已读
    async markAllAsRead({ commit }, userId = null) {
      try {
        const { markAllAsRead } = await import('@/api/assessAlert')
        const response = await markAllAsRead(userId)
        commit('MARK_ALL_AS_READ')
        // 更新未读数量为0
        commit('SET_UNREAD_COUNT', 0)
        return response.data // 返回后端响应数据
      } catch (error) {
        console.error('全部标记已读失败:', error)
        throw error
      }
    },
    
    // 批量标记多个用户的全部预警为已读
    async batchMarkAllAsRead({ commit }, userIds) {
      try {
        const { batchMarkAllAsRead } = await import('@/api/assessAlert')
        const response = await batchMarkAllAsRead(userIds)
        
        if (response.code === 200) {
          // 重新获取待办列表以更新状态
          await this.dispatch('todo/fetchTodoList')
          return response.data
        }
        throw new Error(response.msg || '批量标记失败')
      } catch (error) {
        console.error('批量标记已读失败:', error)
        throw error
      }
    },
    
    // 删除待办任务
    async removeTodo({ commit }, id) {
      try {
        const { deleteWarning } = await import('@/api/assessAlert')
        await deleteWarning(id)
        commit('REMOVE_TODO', id)
      } catch (error) {
        console.error('删除待办任务失败:', error)
        throw error
      }
    },
    
    // 批量删除
    async batchRemoveTodo({ commit }, ids) {
      try {
        const { batchDeleteWarnings } = await import('@/api/assessAlert')
        await batchDeleteWarnings(ids)
        commit('BATCH_REMOVE_TODO', ids)
      } catch (error) {
        console.error('批量删除失败:', error)
        throw error
      }
    },
    
    // 获取未读数量
    async fetchUnreadCount({ commit }, userId = null) {
      try {
        const { getUnreadCount } = await import('@/api/assessAlert')
        const response = await getUnreadCount(userId)
        if (response.code === 200) {
          commit('SET_UNREAD_COUNT', response.data || 0)
          return response.data || 0
        }
        return 0
      } catch (error) {
        console.error('获取未读数量失败:', error)
        return 0
      }
    },
    
    // 清空待办列表（用于测试）
    clearTodoList({ commit }) {
      commit('CLEAR_TODO_LIST')
    }
  },
  
  getters: {
    // 待办列表
    todoList: state => state.todoList,
    // 未读数量
    unreadCount: state => state.unreadCount,
    // 未读待办列表
    unreadTodoList: state => state.todoList.filter(item => !item.isRead),
    // 已读待办列表
    readTodoList: state => state.todoList.filter(item => item.isRead),
    // 是否正在加载
    loading: state => state.loading,
    // 是否有未读
    hasUnread: state => state.unreadCount > 0
  }
}

export default todo
